import prompt from '@system.prompt';
import router from '@system.router';
import util from '../../common/js/util.js';

// 来源  作为后台数据,不渲染(数据量过大,强行渲染会出现各种奇葩bug)
// list: [],
let contentList = []

export default {
    data: {
        id: 0,
        book: {},
        // 前台目录数据,需要渲染
        showContent: {
            index: 0,
            page: 1,
            pageSize: 10,
            //[{id,site},{id,site}]
            webs: [],
            chapterList: [],
            contentsId: 0,
            // 总页数
            sumPage: 0,
            // 顺序
            order: true,
            // 总章节数
            sumChapter: 0,
            // 最新章节
            newChapter: {},
            // 请求中 true, 请求完成 false
            stateLoading: false,
            // 网络状态  true 没网 , false 正常
            isError: false,
        },
        // 获取大tab的索引
        currentIndex: 0,
        // 当前小说来源索引
        index: 0,
        // 小说是否已被收藏
        isShelf: false,
        // 收藏量
        collectionNum: 0,
        // 点击量
        clickNum: 0,
        // 书的评分
        avgScore: 0,
        // 最新章节,已废弃
        newChapter: {},
        // 获取本书评论信息
        comment: {
            list: [],
            // -2 初始化 , -1 请求失败
            count: -2,
            page: 1,
            pageSize: 10,
            isLoading: false,
            // 评论
            areaLines: 1,
            areaValue: "",
            areaHeight: 40,
            areaHint: "发一条友善的评论吧~",
            reply: -1
        },
        // 作者其他小说
        elseBooks: []
    },
    // 评论内容编辑中
    areaChange: function (e) {
        let lines = e.lines < 1 ? 1 : e.lines
        lines = lines > 4 ? 4 : lines
        // this.comment.areaHeight = e.height
        this.comment.areaLines = lines
        this.comment.areaValue = e.text
    },
    // 取消评论
    blurComment: function () {
        this.comment.areaLines = 1
        this.comment.areaValue = ""
        this.comment.areaHeight = 40
        this.comment.areaHint = `发一条友善的评论吧~`
        this.comment.reply = -1
    },
    //回复
    reply: function (commentId, nickname) {
        this.comment.areaHint = `回复 @${nickname}:`

        this.comment.reply = commentId

        this.$element("commentArea").focus({
            focus: true
        })
    },
    // 发布评论
    publish: function () {
        let that = this
        that.comment.areaValue = that.comment.areaValue.replace(" ", '')

        if (that.comment.areaValue == "") {
            return
        }

        let data = {
            bookId: that.id,
            content: that.comment.areaValue
        }

        if (this.comment.reply != -1) {
            data.reply = this.comment.reply
        }

        if (this.$app.$def.globalData.token) {
            this.$app.$def.http({
                url: `/comment/publish`,
                data: data
            }).then(res => {
                if (res.status == 200) {
                    this.blurComment()

                    // 发布成功后刷新评论列表
                    that.refreshComments()

                    prompt.showToast({
                        message: "评论成功"
                    })
                }
            })
        }
    },
    onInit() {
        let that = this
        // 请求本书信息
        this.$app.$def.http({
            url: `/book/` + that.id
        }).then(res => {
            if (res.status == 200) {
                let book = res.data;

                if (!that.book.name) {
                    that.book = book
                }
                // 获取同作者的其他小说
                that.getElse();
            } else {
                prompt.showToast({
                    message: "刷新重试"
                });
            }
        }).catch(error => {
            prompt.showToast({
                message: "刷新重试"
            });
        });


        this.getContents();


        // 获取本书收藏量
        this.$app.$def.http({
            url: "/shelf/shelfNum",
            data: {
                bookId: this.id
            }
        }).then(res => {
            if (res.status == 200) {
                that.collectionNum = res.data
            }
        });


        // 增加点击历史  接口废弃
        /*   this.$app.$def.http({
            url: "/history/add",
            data: {
                bookId: this.id
            }
        })*/

        // 获取本书点击量
        this.$app.$def.http({
            url: "/history/click",
            data: {
                bookId: this.id
            }
        }).then(res => {
            if (res.status == 200) {
                that.clickNum = res.data + 1
            }
        });

        // 获取本书评分
        this.getScore()

        this.hasShelf()
    },
    // 获取本书的评分
    getScore() {

        this.$app.$def.http({
            url: "/score/book",
            data: {
                bookId: this.id
            }
        }).then(res => {
            if (res.status == 200) {
                this.avgScore = res.data
            }
        });
    },
    // 判断本书是否被用户收藏
    hasShelf: function () {
        let that = this
        if (this.$app.$def.globalData.token) {

            this.$app.$def.http({
                url: "/shelf/isExit",
                data: {
                    bookId: this.id
                }
            }).then(res => {
                if (res.status == 200) {
                    that.isShelf = res.data;
                }
            });
        }
    },

    // 获取目录信息
    getContents: function () {
        // 请求目录信息
        let that = this

        if (this.showContent.stateLoading) {
            return
        }
        this.showContent.isError = false

        this.showContent.stateLoading = true


        this.$app.$def.http({
            url: `/contents/vo/` + that.id
        }).then(res => {

            console.info(JSON.stringify(res))

            if (res.status == 200) {

                this.showContent.stateLoading = false

                if (!that.book.name) {
                    that.book = res.data.book
                }

                let temp = [];
                that.showContent.webs = []
                res.data.list.forEach(ele => {
                    if (ele.contents && ele.contents.content != null && ele.contents.content != "") {

                        if (typeof (ele.contents.content) == 'string') {
                            ele.contents.content = JSON.parse(ele.contents.content)
                        }

                        ele.contents.newChapter = ele.contents.content[ele.contents.content.length - 1]

                        let length = ele.contents.content.length

                        that.showContent.newChapter = ele.contents.content[length - 1]

                        that.showContent.sumChapter = length

                        that.showContent.contentsId = ele.contents.id

                        that.showContent.chapterList = ele.contents.content.slice((that.showContent.page - 1) * that.showContent.pageSize, that.showContent.page * that.showContent.pageSize)

                        that.showContent.sumPage = (length % that.showContent.pageSize == 0) ? parseInt(length / that.showContent.pageSize) : parseInt(length / that.showContent.pageSize + 1)

                        that.showContent.webs.unshift({
                            site: ele.web.site,
                            id: ele.web.id
                        })
                        temp.unshift(ele)
                    } else {
                        that.showContent.webs.push({
                            site: ele.web.site,
                            id: ele.web.id
                        })
                        temp.push(ele)
                    }
                })
                contentList = temp

            } else {
                this.showContent.stateLoading = false
            }
        }).catch(error => {
            this.showContent.stateLoading = false
            this.showContent.isError = true
        });
    },

    // 更换小说来源
    change: function (e) {

        let index = e.value

        let that = this

        if (contentList[index].contents.content == null || contentList[index].contents.content == '') {

            this.$app.$def.http({
                url: `/contents/vo/${that.id}/${contentList[index].web.id}`
            }).then(res => {
                // console.info(JSON.stringify(res))
                if (res.status == 200) {
                    // 请求成功时切换状态
                    contentList[index].contents.content = res.data
                    contentList[index].contents.newChapter = res.data[res.data.length - 1]
                    that.index = index


                    // showContent 变更
                    that.showContent.index = index
                    that.showContent.page = 1
                    that.showContent.order = true
                    that.showContent.contentsId = contentList[index].contents.id
                    that.showContent.newChapter = contentList[index].contents.content[contentList[index].contents.content.length - 1]
                    that.showContent.sumChapter = contentList[index].contents.content.length

                    let start = (this.showContent.page - 1) * this.showContent.pageSize
                    let end = this.showContent.page * this.showContent.pageSize
                    this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end)

                } else {
                    prompt.showToast({
                        message: "刷新重试",
                        duration: 2000
                    });
                }
            }).catch(error => {
                prompt.showToast({
                    message: "网络错误",
                    duration: 2000
                });
            });
        } else {
            that.index = index

            that.showContent.index = index
            that.showContent.page = 1
            that.showContent.order = true
            that.showContent.contentsId = contentList[index].contents.id
            that.showContent.newChapter = contentList[index].contents.content[contentList[index].contents.content.length - 1]
            that.showContent.sumChapter = contentList[index].contents.content.length

            let start = (this.showContent.page - 1) * this.showContent.pageSize
            let end = this.showContent.page * this.showContent.pageSize
            this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end)
        }

    },
    prePage: function () {
        this.showContent.page = (this.showContent.page > 1) ? (this.showContent.page - 1) : 1
        this.goPage()
    },
    nextPage: function () {
        this.showContent.page = (this.showContent.page < this.showContent.sumPage) ? (this.showContent.page + 1) : this.showContent.sumPage
        this.goPage()
    },
    pageChange: function (e) {
        // e.newValue为string类型
        this.showContent.page = parseInt(e.newValue)
        this.showContent.page = (this.showContent.page > 1) ? this.showContent.page : 1
        this.showContent.page = (this.showContent.page < this.showContent.sumPage) ? this.showContent.page : this.showContent.sumPage
        this.goPage()
    },
    goPage: function () {
        if (this.showContent.order) {
            let start = (this.showContent.page - 1) * this.showContent.pageSize
            let end = this.showContent.page * this.showContent.pageSize
            this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end)
        } else {
            let end = this.showContent.sumChapter - (this.showContent.page - 1) * this.showContent.pageSize

            let start = this.showContent.sumChapter - this.showContent.page * this.showContent.pageSize

            start = start > 0 ? start : 0;

            this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end).reverse()
        }
    },
    computed: {
        // 将总页数变为页码列表
        numToList: function () {
            let list = []
            for (let i = 0;i < this.showContent.sumPage; i++) {
                list.push(i + 1)
            }
            return list
        }
    },
    reverse: function () {
        if (!this.showContent.order) {
            // 倒序变正序
            let start = (this.showContent.page - 1) * this.showContent.pageSize
            let end = this.showContent.page * this.showContent.pageSize
            this.showContent.order = true
            this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end)
        } else {
            // 正序变倒序
            let end = this.showContent.sumChapter - (this.showContent.page - 1) * this.showContent.pageSize
            let start = this.showContent.sumChapter - this.showContent.page * this.showContent.pageSize
            start = start > 0 ? start : 0;
            this.showContent.order = false
            this.showContent.chapterList = contentList[this.showContent.index].contents.content.slice(start, end).reverse()
        }
    },

    // 获取同作者的其他小说
    getElse: function () {
        let that = this
        // 获取本书的评分
        this.$app.$def.http({
            url: "/book/author/" + this.book.author
        }).then(res => {
            if (res.status == 200) {
                that.elseBooks = res.data
            }
        });
    },

    // 获取评论
    getComments: function () {

        let that = this

        if (this.comment.count > -1 && this.comment.count <= this.comment.list.length) {
            return
        }

        if (this.comment.isLoading) {
            return
        }

        this.comment.isLoading = true

        this.$app.$def.http({
            url: "/comment/list",
            data: {
                bookId: that.id,
                page: that.comment.page,
                pageSize: that.comment.pageSize
            }
        }).then(res => {

            if (res.status == 200) {
                let temp = [];
                that.comment.count = res.data.count
                that.comment.page = that.comment.page + 1;
                that.comment.list = temp.concat(that.comment.list, res.data.list);
            } else {
                that.comment.count = -1
            }

            that.comment.isLoading = false


        }).catch(err => {
            that.comment.count = -1
            that.comment.isLoading = false
        })

    },
    refreshComments: function () {
        let that = this
        that.comment.page = 1
        that.comment.list = []
        that.comment.count = -2
        that.getComments()
    },


    // 大tab切换
    tabChange: function (e) {
        this.currentIndex = e.index
        // 评论初始化
        if (this.currentIndex == 2 && !this.comment.isLoading && this.comment.count == -2) {
            this.refreshComments();
        }
    },

    // 收藏或取消收藏
    shelfChange: function () {
        if (this.$app.$def.globalData.token) {
            if (!this.isShelf) {
                // this.isShelf = true
                this.addShelf()
            } else {
                this.removeShelf()
            }
        } else {
            prompt.showToast({
                message: "请先登录"
            })
        }

    },
    // 加入收藏
    addShelf: function () {
        console.info("========addShelf==========")
        let that = this
        this.$app.$def.http({
            url: `/shelf/add`,
            data: {
                bookId: that.id
            }
        }).then(res => {
            console.info(JSON.stringify(res))
            if (res.status == 200) {
                that.isShelf = true
                that.collectionNum = that.collectionNum + 1
            }
        })
    },
    // 取消收藏
    removeShelf: function () {
        console.info("========removeShelf==========")
        let that = this
        this.$app.$def.http({
            url: `/shelf/delete`,
            data: {
                bookId: that.id
            }
        }).then(res => {
            console.info(JSON.stringify(res))
            if (res.status == 200) {
                that.isShelf = false
                that.collectionNum = that.collectionNum - 1
            }
        })
    },

    goContents: function (id) {
        router.push({
            uri: "pages/contents/contents",
            params: {
                id: id
            }
        })
    },

    // 起点中文网图片需要处理才能显示出来
    imgExchange: function (img) {
        return util.imgExchange(img)
    },
    formatTime: function (time) {
        return util.formatTime(time)
    }
}
